//
//  ContactsViewModel.swift
//  WeChatClient
//
//  Created by AI Assistant on 2025/10/31.
//

import Foundation
import Combine

class ContactsViewModel: ObservableObject {
    @Published var contacts: [User] = []
    @Published var searchText: String = ""
    @Published var selectedContact: User?
    
    private let mockDataService = MockDataService.shared
    
    init() {
        loadContacts()
    }
    
    func loadContacts() {
        contacts = mockDataService.getMockUsers().sorted { $0.displayName < $1.displayName }
    }
    
    var filteredContacts: [User] {
        if searchText.isEmpty {
            return contacts
        } else {
            return contacts.filter { contact in
                contact.displayName.localizedCaseInsensitiveContains(searchText) ||
                contact.userName.localizedCaseInsensitiveContains(searchText) ||
                contact.phoneNumber.contains(searchText)
            }
        }
    }
    
    var groupedContacts: [String: [User]] {
        let filtered = filteredContacts
        let grouped = Dictionary(grouping: filtered) { contact in
            let firstChar = String(contact.displayName.prefix(1))
            // 简单的拼音首字母分组（这里简化处理）
            if firstChar.rangeOfCharacter(from: CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) != nil {
                return firstChar.uppercased()
            } else {
                return "#"
            }
        }
        return grouped
    }
    
    var sortedSectionKeys: [String] {
        let keys = Array(groupedContacts.keys)
        let letterKeys = keys.filter { $0 != "#" }.sorted()
        let symbolKeys = keys.filter { $0 == "#" }
        return letterKeys + symbolKeys
    }
    
    func selectContact(_ contact: User) {
        selectedContact = contact
    }
}
